const express = require('express');
const path = require('path');
const { execSync, exec } = require('child_process');
const app = express();
const PORT = 8000;

const gitConfigService = require('./gitConfigService');
const codeSearchService = require('./codeSearchService');



// 静态资源托管
app.use(express.static(path.join(__dirname, 'public')));

// 配置管理接口
app.use(express.json());

// 获取git仓库配置
app.get('/api/config', (req, res) => {
  gitConfigService.getGitConfig((err, config) => {
    if (err) {
      return res.status(500).json({ error: '读取配置文件失败' });
    }
    res.json(config);
  });
});
// 新增git仓库配置
app.post('/api/config', (req, res) => {
  const newRepo = req.body;
  gitConfigService.addGitRepo(newRepo, err => {
    if (err) return res.status(500).json({ error: '写入配置文件失败' });
    res.json({ success: true });
  });
});
// 修改git仓库配置
app.put('/api/config/:index', (req, res) => {
  const idx = parseInt(req.params.index, 10);
  const updateRepo = req.body;
  gitConfigService.updateGitRepo(idx, updateRepo, err => {
    if (err) return res.status(500).json({ error: err.message || '写入配置文件失败' });
    res.json({ success: true });
  });
});
// 删除git仓库配置
app.delete('/api/config/:index', (req, res) => {
  const idx = parseInt(req.params.index, 10);
  gitConfigService.deleteGitRepo(idx, err => {
    if (err) return res.status(500).json({ error: err.message || '写入配置文件失败' });
    res.json({ success: true });
  });
});
// 代码搜索接口
app.post('/api/search', (req, res) => {
  const keyword = req.query.q ? req.query.q.trim() : '';
  codeSearchService.pullGitReposFromReq(req.body.repos, (err, repos) => {
    if (err) {
      return res.status(500).json({ error: err });
    }
    codeSearchService.searchCode(keyword, repos, (err, results) => {
      if (err) {
        return res.status(500).json({ error: err });
      }
      res.json({ results });
    });
  });
});
// 兜底路由（可选）
app.use((req, res) => {
  res.status(404).send('页面未找到');
});
app.listen(PORT, () => {
  console.log(`服务器已启动，访问 http://localhost:${PORT}`);
});